package com.endoc.base.activity;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;

import com.endoc.base.loadsir.EmptyCallback;
import com.endoc.base.loadsir.ErrorCallback;
import com.endoc.base.loadsir.LoadingCallback;
import com.endoc.base.viewmodel.BaseViewModel;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

public abstract class MvvmActivity<VM extends BaseViewModel,Databinding extends ViewDataBinding> extends AppCompatActivity  implements IBaseView {
   public Databinding basedatabinding;
    public VM vm;
    private LoadService mLoadService;

    /**
     * @return 必须返回一个资源的id
     */
    @LayoutRes
    public  abstract int getLayoutId();
    public  abstract VM getViewModel();
    public  abstract int getBindingVariable();




    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindLayout();
    }

    private void bindLayout(){
        basedatabinding = DataBindingUtil.setContentView(this, getLayoutId());
        if(vm==null){
            vm=getViewModel();
        }
        //如果xml中有设置数据
        if(getBindingVariable()>0){
            //进行数据绑定,将当前的vm给设置进去
            basedatabinding.setVariable(getBindingVariable(),vm);
        }
        //执行绑定,具体为什么我也不知道
        basedatabinding.executePendingBindings();
    }

    @Override
    public void onRefreshEmpty() {
        if(mLoadService != null) {
            mLoadService.showCallback(EmptyCallback.class);
        }
    }

    @Override
    public void onRefreshFailure(String message) {
        if(mLoadService != null) {
            mLoadService.showCallback(ErrorCallback.class);
        }
    }

    @Override
    public void showLoading() {
        if (mLoadService != null) {
            mLoadService.showCallback(LoadingCallback.class);
        }
    }

    @Override
    public void showContent() {
        if (mLoadService != null) {
            mLoadService.showSuccess();
        }
    }

    public abstract void onRetryClick();
    public void setLoadsirView(View view){
        mLoadService = LoadSir.getDefault().register(view, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                onRetryClick();
            }
        });
    }

}
